package com.lcd.ssm.util;


import com.lcd.ssm.domain.Menu;
import com.lcd.ssm.domain.Permission;
import com.lcd.ssm.service.IPermissionService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Iterator;
import java.util.List;

@Component
public class PermissionUtil {
    private static final Logger logger = LoggerFactory.getLogger(PermissionUtil.class);
    private static IPermissionService permissionService;
    @Autowired
    public void setPermissionService(IPermissionService permissionService) {
        PermissionUtil.permissionService = permissionService;
    }

    //核心的一些逻辑，返回true代表通过权限验证，返回false 说明没有对应的权限
    public static boolean judge(String rbacStr) {
        logger.info("进入权限校验,地址为:{}",rbacStr);
        //初始化加载权限表里面的资源，第一次初始化的时候才调用
        if(CommonUtil.allPermissions.isEmpty()){
            List<Permission> permissions = permissionService.selectAll();
            for (Permission permission : permissions) {
                CommonUtil.allPermissions.add(permission.getResource());
            }
        }
        //当前请求的资源是否在权限表里面，如果不存在，说明就不用做权限认证，则放行
        if (CommonUtil.allPermissions.contains(rbacStr)) {
            List<String> currentUserResource = (List<String>) UserContext.getRequest().getSession().getAttribute(UserContext.PERMISSIONS_SESSION);
            //说明完全匹配，则放行
            if (currentUserResource.contains(rbacStr)) {
                return true;
            }else {
                String all = rbacStr.split(":")[0]+":ALL";
                //如果不是完全匹配，那么看看是否拥有all的权限匹配
                return currentUserResource.contains(all);
            }
        }else {
            return true;
        }

    }

    public static void checkCurrentUserMenu(List<Menu> menuList) {
        List<String> permissionList= (List<String>) UserContext.getRequest().getSession().getAttribute(UserContext.PERMISSIONS_SESSION);
        Iterator<Menu> iterator = menuList.iterator();
        while (iterator.hasNext()) {
            Menu menu = iterator.next();
            //如果菜单的权限表达式不为空，说明需要受到权限控制，如果权限集合不包含这个菜单，那么需要删除
            if (StringUtils.isNotBlank(menu.getFunction()) && !permissionList.contains(menu.getFunction())) {
                iterator.remove();
            }
            //到这里的话说明这个菜单是有权限的，那么就检查一下这个菜单的儿子菜单那是否有权限
            if(!CollectionUtils.isEmpty(menu.getChildren())){
                checkCurrentUserMenu(menu.getChildren());
            }
        }
    }

}
